<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-21 15:55:09
 * @LastEditTime: 2020-10-28 15:22:06
 * @LastEditors: Please set LastEditors
 -->
<style scoped>
.ivu-table-wrapper {
  overflow: visible;
}
</style>
<template>
  <div>
    <!-- <Layout :style="{padding: '0 5px 1px'}">
             <Content :style="{padding: '24px', minHeight: '650px', background: '#fff'}">
                 
             </Content>
         </Layout> -->
    <div style="text-align:left;overflow: auto;">
      <Button
        type="primary"
        @click="
          addConfigureBt = true;
          cancelsmtConfigureInfo('formValidate');
          addConfigureBtTitle = '创建配置';
        "
      >
        <Icon type="md-add" />
        创建配置
      </Button>
      <Input
        suffix="ios-search"
        placeholder="请输入名称"
        clearable
        style="width: auto"
        v-model="btnNameValue"
        @on-change="
          connfigerCurrentPage = 1;
          getOutbandcaptureInfoList();
        "
      />
      <Select filterable
        v-model="configerSystypeOfReach"
        filterable
        style="width:180px;"
        clearable
        transfer
        placeholder="请选择系统"
        @on-change="
          connfigerCurrentPage = 1;
          getOutbandcaptureInfoList();
        "
      >
        <Option value="lin">Linux</Option>
        <Option value="win">Windows</Option>
      </Select>
      <DatePicker
        type="daterange"
        placeholder="请选择日期"
        style="width: 200px"
        :editable="false"
        v-model="configerDateSelected"
        @on-change="dateSelected"
        :options="options3"
      ></DatePicker>
      <Select filterable
        v-model="configerTimeIntervalOfReach"
        filterable
        style="width:180px;"
        clearable
        transfer
        placeholder="请选择采集周期"
        @on-change="
          connfigerCurrentPage = 1;
          getOutbandcaptureInfoList();
        "
      >
        <Option value="2">2S</Option>
        <Option value="5">5S</Option>
        <Option value="10">10S</Option>
        <Option value="20">20S</Option>
        <Option value="30">30S</Option>
      </Select>
      <!-- <Button type="primary"  @click="getOutbandcaptureInfoList">搜索</Button> -->
      <Page
        :total="pageCount"
        show-total
        style="float:right;"
        show-sizer
        show-elevator
        :current="connfigerCurrentPage"
        :page-size="configerItemPage"
        @on-change="switchineConfigerCurrentPage"
        @on-page-size-change="switchConfigerItemPage"
        transfer
      />
    </div>

    <Table
      :columns="tbTitle"
      :data="tbData"
      style="margin-top:10px;"
      :show-header="true"
    ></Table>
    <Modal
      v-model="addConfigureBt"
      :title="addConfigureBtTitle"
      :loading="loading"
      width="630px;"
      :mask-closable="false"
      @on-ok="submitConfigureInfo('formValidate')"
      @on-cancel="cancelsmtConfigureInfo('formValidate')"
    >
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="95">
        <FormItem label="名称" prop="name">
          <Input v-model="formValidate.name" placeholder="请输入名称" :maxlength="64"></Input>
        </FormItem>
        <FormItem label="采集方式" prop="allData">
          <RadioGroup v-model="formValidate.allData">
            <Radio label="True">全量</Radio>
            <Radio label="False">增量</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="采集间隔" prop="interval">
          <RadioGroup v-model="formValidate.interval">
            <Radio label="2">2s</Radio>
            <Radio label="5">5s</Radio>
            <Radio label="10">10s</Radio>
            <Radio label="20">20s</Radio>
            <Radio label="30">30s</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="操作系统" prop="systemType">
          <Select filterable v-model="formValidate.systemType" @on-change="getCmdsData">
            <Option :value="sys.id.toString()" v-for="(sys, index) in osTypeList" :key="index">{{
              sys.osName
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="类型" prop="speedType">
          <RadioGroup v-model="formValidate.speedType" @on-change="judgeSpeedType">
            <Radio label="F">快速</Radio>
            <Radio label="S">慢速</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="采集指令" prop="cmds" style="height:300px">
          <font color="red" style="font-size:18px;margin-left: -70px;float: left;">*</font>
          <div>
            <Transfer
              ref="transfer"
              :titles="['源指令列表', '目的指令列表']"
              :operations="[$t('del'), $t('add')]"
              :list-style="listStyle"
              :render-format="renderData"
              :data="transferData"
              :target-keys="transferTargetKeys"
              :selected-keys="transferSelectedKeys"
              filterable
              :filter-method="filterMethod"
              @on-change="handleChange"
            >
            </Transfer>
          </div>
        </FormItem>
        <FormItem label="可见性" prop="visibility">
          <RadioGroup v-model="formValidate.visibility">
            <!-- <Radio label="public" >公共</Radio> -->
            <Radio label="share">共享</Radio>
            <Radio label="private">私有</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="配置描述" prop="description">
          <Input
            v-model="formValidate.description"
            type="textarea"
            :rows="2"
            :maxlength="200"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="delConfigureMd" title="删除配置" @on-ok="ok4delConfigureMd">
      <div style="text-align:center;font-size:15px;">
        确认要删除配置：" <strong>{{ this.currConfigureName }}</strong> " 吗？
      </div>
    </Modal>
    <Modal v-model="detailConfigureMd" title="配置详情">
      <Table stripe :columns="detailTbTitle" :data="detailTbData" :show-header="false"></Table>
    </Modal>
  </div>
</template>
<!-- <script src="../../../static/const.js"></script> -->
<script>
import axios from '@/libs/axios1';
import TableTooltip from '@/view/drill_compete/page/tableTooltip.vue';
const validateName = (rule, value, callback) => {
  var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
  value = value.replace(/\s*/g, '');
  if (!value) {
    callback('请填写名字');
  } else {
    if (myReg.test(value)) {
      callback('名字不能包含特殊字符');
    } else {
      callback();
    }
  }
};
export default {
  name: 'outbandCaptureCollect',
  components: { TableTooltip },
  data() {
    return {
      options3: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
        shortcuts: [
              {
                  text: '近一周',
                  value () {
                      const end = new Date();
                      const start = new Date();
                      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                      return [start, end];
                  }
              },
              // {
              //     text: '近一个月',
              //     value () {
              //         const end = new Date();
              //         const start = new Date();
              //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              //         return [start, end];
              //     }
              // },
              // {
              //     text: '近三个月',
              //     value () {
              //         const end = new Date();
              //         const start = new Date();
              //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              //         return [start, end];
              //     }
              // }
          ]
      },
      configerItemPage: 10,
      connfigerCurrentPage: 1,
      tableHeight: '',
      btnNameValue: '',
      configerSystypeOfReach: '',
      configerStartTime: '',
      configerEndTime: '',
      configerDateSelected: '',
      timeInterval: 0,
      configerTimeIntervalOfReach: '',
      tbTitle: [
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '名称',
          key: 'name',
          align: 'center',
          minWidth: 100,
          tooltip: true
          // render: (h, params) => {
          //     return h('div', [
          //         h('a', {
          //             props: {size: 'small'},
          //             style: {marginRight: '5px'},
          //             on: {
          //                     click: () => {
          //                         this.getConfigureInfo(params)
          //                 }
          //             }
          //         }, params.row.name)
          //     ]);
          // }
        },
        {
          title: '系统',
          key: 'description',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            return h(
              'div',
              {},
              params.row.data.osinfo
                .split(';')[0]
                .split('=')[1]
                .replace(/\"/g, '')
            );
          }
        },
        {
          title: '采集间隔(/S)',
          key: 'description',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            return h(TableTooltip, {
              props: {
                content: params.row.data.interval,
                width: 100,
                placement: 'bottom'
              }
            });
            //  return h('div', {}, params.row.data.interval);
          }
        },
        {
          title: '采集指令',
          key: 'description',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            return h(TableTooltip, {
              props: {
                content: params.row.data.cmds.map((item) => item.cmd).join('\n'),
                width: 100,
                placement: 'bottom'
              }
            });
            // if (params.row.data.cmds && params.row.data.cmds.length != 0) {
            //   let value = params.row.data.cmds.map((item) => {
            //     return h('div', {}, item.cmd);
            //   });
            //   return h('div', {}, value);
            // }
          }
        },
        {
          title: 'profile',
          key: '',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            return h(TableTooltip, {
              props: {
                content: params.row.data.profile,
                width: 100,
                placement: 'bottom'
              }
            });
            //  return h('div', {}, params.row.data.profile);
          }
        },
        {
          title: '可见性',
          key: '',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            let visibilityValue = params.row.visibility;
            if (visibilityValue == 'public') {
              visibilityValue = '公共';
            } else if (visibilityValue == 'share') {
              visibilityValue = '共享';
            } else if (visibilityValue == 'private') {
              visibilityValue = '私有';
            }
            return h('div', {}, visibilityValue);
          }
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center',
          minWidth: 140,
          tooltip: true
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'center',
          minWidth: 100,
          tooltip: true
          // render:(h,params)=>{
          //     return h('div',{}, params.row.creatorName)
          //     // console.log(params)
          //     // if(params.index==0||params.index==3||params.index==4){
          //     //     return h('div',{}, '贾海林')
          //     // }else{
          //     //     return h('div',{}, params.row.creatorName)
          //     // }

          // }
        },
        {
          title: '描述',
          key: 'description',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            return params.row.description
              ? h(TableTooltip, {
                  props: {
                    content: params.row.description,
                    width: 100,
                    placement: 'bottom'
                  }
                })
              : h('span', '无');
          }
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          width: 200,
          render: (h, params) => {
            // if(params.index==0||params.index==3||params.index==4){
            //     return;
            // }else{
            //     // return h('div',{}, params.row.creatorName)
            // }
            return h('div', [
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除此配置吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.removeInfo(params);
                    },
                    'on-cancel': () => {}
                  }
                },
                [
                  h(
                    'Button',
                    {
                      props: {
                        type: 'error',
                        size: 'small'
                      },
                      style: {
                        margin: '5px'
                      }
                    },
                    '删除配置'
                  )
                ]
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                    // style:{margin:'10px'}
                  },
                  style: {
                    margin: '5px'
                  },
                  on: {
                    click: () => {
                      this.modifyInfo(params);
                    }
                  }
                },
                '修改配置'
              )
              //     h('Button',{
              //     props:{
              //         type:"primary",
              //         size:'small'
              //         // style:{margin:'10px'}
              //     },
              //     style:{
              //         margin:'5px'
              //     },
              //     on:{
              //         click:()=>{
              //             this.getConfigureInfo(params)
              //         }
              //     }
              // },'查看详情'),
            ]);
          }
        }
      ],
      formValidate: {
        name: '',
        systemType: '',
        description: '',
        allData: 'True',
        speedType: 'S',
        interval: '10',
        visibility: 'share'
      },
      ruleValidate: {
        name: [{ required: true, message: '', trigger: 'blur', validator: validateName }],
        systemType: [{ required: true, message: '请选择操作系统', trigger: 'change' }],
        allData: [{ required: true, message: '请选择采集方式', trigger: 'change' }],
        visibility: [{ required: true, message: '请选择可见性', trigger: 'change' }],
        speedType: [
          { required: true, message: '请选择采集类型', trigger: 'change', type: 'string' }
        ],
        interval: [{ required: true, message: '请选择时间周期', trigger: 'change', type: 'string' }]
      },
      profileValue: '',
      tbData: [],
      detailTbData: [],
      loading: true,
      addConfigureBt: false,
      addConfigureBtTitle: '创建配置',
      currPage: 1,
      pageCount: 0,
      detailConfigureMd: false,
      detailTbTitle: [
        {
          title: '属性',
          key: 'attr'
        },
        {
          title: '值',
          key: 'value'
        }
      ],
      configureDetailInfo: {},
      delConfigureMd: false,
      currConfigureId: '',
      currConfigureName: '',
      osTypeList: {},
      cmdsList: {},
      transferData: [],
      transferTargetKeys: [],
      transferSelectedKeys: [],
      listStyle: {
        width: '200px',
        height: '300px'
      }
    };
  },
  props: ['refreshTaskList'],
  created: function() {
    // this.tableHeight = $(window).height() - 115 ;
    this.getOutbandcaptureInfoList();
    this.getSysType();
  },
  methods: {
    dateSelected(value) {
      console.log(value);
      if (value[0]) {
        this.configerStartTime = String(value[0]) + ' 00:00:00';
        this.configerEndTime = String(value[1]) + ' 23:59:59';
        console.log(this.configerStartTime);
      } else {
        this.configerStartTime = '';
        this.configerEndTime = '';
      }
      this.connfigerCurrentPage = 1;
      this.getOutbandcaptureInfoList();
    },

    change: function(page) {
      this.currPage = page;
      this.getOutbandcaptureInfoList();
    },
    getSysType() {
      let _this = this;
      axios({
        url: '/resource-manager/profile/list/detail',
        method: 'get'
      }).then(function(response) {
        //  response = response.data
        //   console.log(response)
        console.log(response);
        if (response.code != '1') {
          _this.$Message.info(response.message);
        } else {
          _this.osTypeList = response.data.filter(function(item) {
            // if(item.status){
            return item;
            // }
          });
        }
      });
    },
    getOutbandcaptureInfoList() {
      let _this = this;
      axios({
        url: '/tasktemplate/item',
        method: 'get',
        params: {
          page: _this.connfigerCurrentPage,
          size: _this.configerItemPage,
          operation: 'outband_capture',
          name: _this.btnNameValue,
          profile: _this.configerSystypeOfReach,
          startTime: String(_this.configerStartTime),
          endTime: String(_this.configerEndTime),
          interval: _this.configerTimeIntervalOfReach
        }
      }).then(function(response) {
        //  response = response.data
        if (response.code != '1') {
          _this.$Message.info(response.message);
          _this.tbData = [];
        } else {
          _this.tbData = response.data.list.map(function(item) {
            return {
              id: item.id,
              name: item.name,
              description: item.description,
              category: item.category,
              data: item.data,
              createTime: item.createTime,
              creatorName: item.creatorName,
              visibility: item.visibility
            };
          });
          _this.pageCount = response.data.count;
        }
      });
    },
    getConfigureInfo(params) {
      let _this = this;
      _this.detailConfigureMd = true;
      _this.currConfigureId = params.row.id;
      axios({
        url: '/tasktemplate/item/' + _this.currConfigureId,
        method: 'get'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.info(response.message);
        } else {
          _this.configureDetailInfo = response.data;
          _this.detailTbData = [
            { attr: '名称', value: _this.configureDetailInfo.name },
            { attr: '配置描述', value: _this.configureDetailInfo.description },
            { attr: 'profile', value: _this.configureDetailInfo.data.profile },
            { attr: 'osinfo', value: _this.configureDetailInfo.data.osinfo },
            { attr: 'cmds', value: _this.configureDetailInfo.data.cmds },
            { attr: '创建时间', value: _this.configureDetailInfo.createTime },
            { attr: '创建者', value: _this.configureDetailInfo.creatorName },
            { attr: '修改时间', value: _this.configureDetailInfo.lastModifyTime },
            { attr: '修改者', value: _this.configureDetailInfo.modifior }
          ];
        }
      });
    },
    submitConfigureInfo(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (_this.transferTargetKeys.length <= 0) {
          valid = false;
        }
        if (valid) {
          let data = _this.formValidate;
          delete data.systemType;
          console.log(_this.transferTargetKeys);
          data.cmds = _this.transferTargetKeys.map((item) => {
            let cmd = {};
            _this.cmdsList[0].cmds.forEach((data) => {
              if (data.id == item) {
                cmd = {
                  // args:data.essentialarg.split(','),
                  args: data.args.map((tt) => {
                    let str = JSON.stringify(tt);
                    return str;
                  }),
                  cmd: data.name,
                  allData: _this.formValidate.allData
                };
              }
            });
            return cmd;
          });
          data.osinfo = _this.cmdsList[0].content;
          data.profile = _this.cmdsList[0].osName;
          data.style = _this.formValidate.speedType;
          data.interval = _this.formValidate.interval;
          data.name = data.name.replace(/\s*/g, '');
          data.description = _this.formValidate.description;
          data.visibility = _this.formValidate.visibility;
          delete data.speedType;
          if (_this.addConfigureBtTitle == '创建配置') {
            axios({
              url: '/tasktemplate/item/add/capture_outband',
              method: 'post',
              data: data
            }).then(function(response) {
              if (response.code != '1') {
                _this.$Message.error(response.message);
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
              } else {
                _this.connfigerCurrentPage = 1;
                _this.configerItemPage = 10;
                _this.btnNameValue = '';
                _this.configerSystypeOfReach = '';
                _this.configerDateSelected = '';
                _this.configerStartTime = '';
                _this.configerEndTime = '';
                _this.configerTimeIntervalOfReach = '';
                _this.$Message.success('新增配置完成!');
                _this.getOutbandcaptureInfoList();
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
                _this.addConfigureBt = false;
                _this.cancelsmtConfigureInfo('formValidate');
              }
            });
          } else {
            //修改配置
            axios({
              url: '/tasktemplate/item/update/capture_outband/' + _this.currConfigureId,
              method: 'put',
              data: data
            }).then(function(response) {
              if (response.code != '1') {
                _this.$Message.error(response.message);
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
              } else {
                _this.$Message.success('修改配置完成!');
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
                _this.getOutbandcaptureInfoList();
                _this.addConfigureBt = false;
                _this.cancelsmtConfigureInfo('formValidate');
                _this.refreshTaskList();
              }
            });
          }
        } else {
          _this.loading = false;
          _this.$nextTick(() => {
            _this.loading = true;
          });
          _this.$Message.info('请检查内容是否填写完整！');
        }
      });
    },
    cancelsmtConfigureInfo(name) {
      this.$refs[name].resetFields();
      this.formValidate = {
        name: '',
        systemType: '',
        description: '',
        allData: 'True',
        speedType: 'S',
        interval: '10',
        visibility: 'share'
      };
      this.transferData = [];
      this.transferTargetKeys = [];
      // 清空穿梭框搜索条件
      this.$refs.transfer.$children[0].query = '';
      this.$refs.transfer.$children[2].query = '';
      // 清空穿梭框复选框
      this.$refs.transfer.$children[0].toggleSelectAll();
      this.$refs.transfer.$children[2].toggleSelectAll();
    },
    modifyInfo(params) {
      let _this = this;
      _this.currConfigureId = params.row.id;
      axios({
        url: '/tasktemplate/item/' + _this.currConfigureId,
        method: 'get'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.error(response.message);
        } else {
          let tempId = '';
          _this.osTypeList.forEach((item) => {
            if (item.osName == response.data.data.profile) tempId = item.id;
          });
          _this.formValidate = {
            name: response.data.name,
            systemType: tempId.toString(),
            description: response.data.description,
            allData: response.data.data.cmds[0].allData,
            interval: response.data.data.interval,
            visibility: response.data.visibility || 'share'
          };
          _this.formValidate.speedType = response.data.data.style;
          //初始化源指令数据
          _this.getCmdsData(tempId);
          _this.transferTargetKeys = response.data.data.cmds.map((item) => {
            let cmdId = '';
            _this.cmdsList[0].cmds.forEach((data) => {
              if (data.name == item.cmd) {
                cmdId = data.id;
              }
            });
            return cmdId;
          });
          _this.addConfigureBtTitle = '修改配置';
          _this.addConfigureBt = true;
        }
      });
    },
    removeInfo(params) {
      this.currConfigureId = params.row.id;
      this.ok4delConfigureMd();
    },
    ok4delConfigureMd() {
      let _this = this;
      axios({
        url: '/tasktemplate/item/' + _this.currConfigureId,
        method: 'delete'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.error(response.message);
        } else {
          _this.connfigerCurrentPage =
            _this.tbData.length == 1 && _this.connfigerCurrentPage > 1
              ? _this.connfigerCurrentPage - 1
              : _this.connfigerCurrentPage;
          _this.$Message.success('删除配置完成！');
          _this.getOutbandcaptureInfoList();
        }
      });
      _this.delConfigureMd = false;
    },
    getCmdsData(value) {
      let _this = this;
      _this.profileValue = value;
      _this.transferData = [];
      _this.transferTargetKeys = [];
      // 清空穿梭框搜索条件
      this.$refs.transfer.$children[0].query = '';
      this.$refs.transfer.$children[2].query = '';
      // 清空穿梭框复选框
      this.$refs.transfer.$children[0].toggleSelectAll();
      this.$refs.transfer.$children[2].toggleSelectAll();
      if (value) {
        _this.cmdsList = _this.osTypeList.filter(function(item) {
          return item.id == value;
        });
        // console.log(_this.cmdsList)
        if (_this.cmdsList) {
          // _this.transferData = _this.cmdsList[0].cmds.map( item=> {
          //     console.log(item.slevel)
          //     console.log(_this.formValidate.speedType)
          //     if(String(item.slevel)==String(_this.formValidate.speedType)){
          //         return { key:item.id, label:item.name};
          //     }
          // })
          this.cmdsList[0].cmds.forEach(function(item, i) {
            console.log(item.slevel);
            if (String(item.slevel) == String(_this.formValidate.speedType)) {
              _this.transferData.push({
                key: item.id,
                label: item.name,
                // title:,
                description: item.note
              });
            }
          });
        }
      }
    },
    handleChange(newTargetKeys, direction, moveKeys) {
      this.transferTargetKeys = newTargetKeys;
    },
    filterMethod(data, query) {
      return data.label.indexOf(query) > -1;
    },
    judgeSpeedType(value) {
      console.log(value);
      this.getCmdsData(this.profileValue);
    },
    renderData(item) {
      // console.log(item)
      return `<span title="${item.description}">${item.label}</span>`;
    },
    switchineConfigerCurrentPage(numberPage) {
      this.connfigerCurrentPage = numberPage;
      this.getOutbandcaptureInfoList();
    },
    switchConfigerItemPage(numberSize) {
      this.configerItemPage = numberSize;
      this.getOutbandcaptureInfoList();
    },
    handleEmpty() {
      this.btnNameValue = '';
      this.configerSystypeOfReach = '';
      this.configerDateSelected = '';
      this.configerEndTime = '';
      this.configerStartTime = '';
      this.configerTimeIntervalOfReach = '';
      // this.getQgaReadLoopInfoList();
    }
  }
};
</script>
